<template>
	<div style="background-color: #ffffff;margin-top: 40px;height: 55vh;">
		<p class="canvas-title">
			{{ props.info.title }}
		</p>

		<div class="canvas-wrap u-f" ref="wrapRef">
			<div
				style="width: 300px; height: 100%; z-index: 1; display: flex; align-items: center; justify-content: center; flex-shrink: 0;"
				v-if="props.info.image[0] && props.info.type == 'imageLeftCanvas'"
			>
				<img :src="BaseUrl + props.info.image[0]" style="
				margin-top: 130px;
				max-width: 100%; max-height: 100%; object-fit: contain;" />
			</div>
			<div :style="{ 
				border: '1px solid #eee', 
				flex: props.info.type === 'imageLeftCanvas' ? '1' : 'none',
				width: props.info.type === 'imageLeftCanvas' ? 'auto' : '100%'
			}">
				<div class="canvas-toolbar">
					<div class="tool-group">
						<!-- <div class="quick-colors">
							<span v-for="color in quickColors" :key="color"
								:style="{ background: color, border: strokeStyle === color ? '2px solid #1790d5' : '2px solid #fff' }"
								class="color-dot" @click="setColor(color)"></span>
						</div> -->
						<div class="quick-sizes">
							<span v-for="size in quickSizes" :key="size" :style="{
								width: size + 'px',
								height: size + 'px',
								background: strokeStyle,
								border: lineWidth === size ? '2px solid var(--theme-primary)' : '2px solid #fff'
							}" class="size-dot" @click="setSize(size)"></span>
						</div>
						<label v-if="!isEraser" class="color-label">
							<input type="color" v-model="strokeStyle" />
						</label>
						<input type="range" min="1" max="30" v-model="lineWidth" class="slider" />
						<button class="tool-btn" :class="{ active: !isEraser }" @click="isEraser = false">
							<span class="iconfont">&#9998;</span> {{ t('game.canvas.brush') }}
						</button>
						<button class="tool-btn" :class="{ active: isEraser }" @click="isEraser = true">
							<span class="iconfont">&#9003;</span> {{ t('game.canvas.eraser') }}
						</button>
						<!-- <span class="brush-size">{{ lineWidth }}px</span> -->
					</div>
					<div class="tool-group">
						<button class="tool-btn clear-btn" style="margin-left: 20px;" @click="clearCanvas">{{ t('game.canvas.clear') }}</button>
					</div>
				</div>
				<div class="canvas-cursor-wrap" ref="cursorWrapRef">
					<img :src="BaseUrl+props.info.image[0]" v-if="props.info.type == 'imageDefault'" alt="" style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: 1; object-fit: fill;">
					<canvas ref="canvasRef" :width="canvasWidth" :height="canvasHeight" 
						style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 2; background: transparent;"
						@mousedown="startDraw" @mousemove="e => { drawing(e); updateCursor(e) }" @mouseup="endDraw"
						@mouseleave="() => { endDraw(); showCursor = false }" @mouseenter="showCursor = true"
						@touchstart.prevent="startDrawTouch" @touchmove.prevent="drawingTouch" @touchend.prevent="endDraw"></canvas>
					<div v-if="showCursor" class="canvas-cursor" :style="cursorStyle"></div>
				</div>
			</div>

		</div>
	</div>

</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, watchEffect } from 'vue'
import { BaseUrl } from '../../../utils/request'

// 翻译系统
const translationVersion = ref(0)
let t = (key: any, params?: any) => {
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../../i18n/locales/en-US')
		} else {
			langModule = await import('../../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationVersion.value++
	} catch (error) {
		console.error('Failed to load translations:', error)
	}
}

const canvasRef = ref<HTMLCanvasElement | null>(null)
const wrapRef = ref<HTMLDivElement | null>(null)
const isDrawing = ref(false)
const lastPoint = ref({ x: 0, y: 0 })
const lineWidth = ref(4)
const strokeStyle = ref('#1790d5')
const isEraser = ref(false)
const canvasWidth = ref(800)
const canvasHeight = ref(400)
const hasDrawn = ref(false)

const showCursor = ref(false)
const cursorPos = ref({ x: 0, y: 0 })
const cursorWrapRef = ref<HTMLDivElement | null>(null)

const cursorStyle: any = ref({
	left: '0px',
	top: '0px',
	width: '0px',
	height: '0px',
	border: '2px solid #1790d5',
	background: 'transparent',
	position: 'absolute',
	pointerEvents: 'none',
	borderRadius: '50%',
	zIndex: 3,
	boxSizing: 'border-box',
})

const quickColors = ['var(--theme-primary)', '#e57373', '#43a047', '#fbc02d', '#000', '#fff']
const quickSizes = [2, 4, 8, 12, 20]
const props = defineProps({
	info: {
		type: Object,
		default: () => ({})
	}
})

watchEffect(() => {
	cursorStyle.value = {
		left: `${cursorPos.value.x - lineWidth.value / 2}px`,
		top: `${cursorPos.value.y - lineWidth.value / 2}px`,
		width: `${lineWidth.value}px`,
		height: `${lineWidth.value}px`,
		border: `2px solid ${isEraser.value ? '#888' : strokeStyle.value}`,
		background: 'transparent',
		position: 'absolute',
		pointerEvents: 'none',
		borderRadius: '50%',
		zIndex: 3,
		boxSizing: 'border-box',
	}
})

function updateCursor(e: MouseEvent) {
	const rect = canvasRef.value!.getBoundingClientRect()
	cursorPos.value = {
		x: e.clientX - rect.left,
		y: e.clientY - rect.top
	}
}

function resizeCanvas() {
	if (wrapRef.value) {
		const wrapWidth = wrapRef.value.clientWidth
		if (props.info.type === 'imageLeftCanvas') {
			// 减去左边图片区域的300px
			canvasWidth.value = wrapWidth - 300
		} else {
			canvasWidth.value = wrapWidth
		}
		// 设置canvas高度为容器高度减去工具栏高度
		const toolbarHeight = 60 // 工具栏大约60px高度
		canvasHeight.value = Math.max(300, wrapRef.value.clientHeight - toolbarHeight)
	}
}

function getPos(e: MouseEvent | TouchEvent) {
	let x = 0, y = 0
	const rect = canvasRef.value!.getBoundingClientRect()
	if (e instanceof MouseEvent) {
		x = (e.clientX - rect.left) * (canvasRef.value!.width / rect.width)
		y = (e.clientY - rect.top) * (canvasRef.value!.height / rect.height)
	} else if (e.touches && e.touches.length) {
		x = (e.touches[0].clientX - rect.left) * (canvasRef.value!.width / rect.width)
		y = (e.touches[0].clientY - rect.top) * (canvasRef.value!.height / rect.height)
	}
	return { x, y }
}

function startDraw(e: MouseEvent) {
	isDrawing.value = true
	lastPoint.value = getPos(e)
}
function drawing(e: MouseEvent) {
	if (!isDrawing.value) return
	
	// 标记已经有绘制内容
	hasDrawn.value = true
	
	const ctx = canvasRef.value!.getContext('2d')!
	ctx.lineCap = 'round'
	ctx.lineJoin = 'round'
	ctx.lineWidth = lineWidth.value
	
	if (isEraser.value) {
		ctx.globalCompositeOperation = 'destination-out'
	} else {
		ctx.globalCompositeOperation = 'source-over'
		ctx.strokeStyle = strokeStyle.value
	}
	
	ctx.beginPath()
	ctx.moveTo(lastPoint.value.x, lastPoint.value.y)
	const pos = getPos(e)
	ctx.lineTo(pos.x, pos.y)
	ctx.stroke()
	lastPoint.value = pos
}
function endDraw() {
	isDrawing.value = false
}
function startDrawTouch(e: TouchEvent) {
	isDrawing.value = true
	lastPoint.value = getPos(e)
}
function drawingTouch(e: TouchEvent) {
	if (!isDrawing.value) return
	
	// 标记已经有绘制内容
	hasDrawn.value = true
	
	const ctx = canvasRef.value!.getContext('2d')!
	ctx.lineCap = 'round'
	ctx.lineJoin = 'round'
	ctx.lineWidth = lineWidth.value
	
	if (isEraser.value) {
		ctx.globalCompositeOperation = 'destination-out'
	} else {
		ctx.globalCompositeOperation = 'source-over'
		ctx.strokeStyle = strokeStyle.value
	}
	
	ctx.beginPath()
	ctx.moveTo(lastPoint.value.x, lastPoint.value.y)
	const pos = getPos(e)
	ctx.lineTo(pos.x, pos.y)
	ctx.stroke()
	lastPoint.value = pos
}
function clearCanvas() {
	const ctx = canvasRef.value!.getContext('2d')!
	ctx.clearRect(0, 0, canvasRef.value!.width, canvasRef.value!.height)
	// 重置绘制状态
	hasDrawn.value = false
}
function setColor(color: string) {
	strokeStyle.value = color
}
function setSize(size: number) {
	lineWidth.value = size
}

function getCanvasData() {
	// 如果用户没有进行绘制，返回null
	if (!hasDrawn.value) {
		return Promise.resolve(null)
	}
	
	if (canvasRef.value) {
		// imageLeftCanvas类型：左侧图片只是参考，不保存到canvas中
		if (props.info.type === 'imageLeftCanvas') {
			// 直接返回canvas绘制内容，不包含左侧参考图片
			return Promise.resolve(canvasRef.value.toDataURL('image/png'))
		}
		
		// 其他类型：需要合并背景图片和绘制内容
		const tempCanvas = document.createElement('canvas')
		tempCanvas.width = canvasRef.value.width
		tempCanvas.height = canvasRef.value.height
		const tempCtx = tempCanvas.getContext('2d')!
		
		// 如果有背景图片，先绘制背景图片
		if (props.info.image && props.info.image[0]) {
			const img = new Image()
			img.crossOrigin = 'anonymous' // 处理跨域问题
			
			return new Promise<string>((resolve) => {
				img.onload = () => {
					// 绘制背景图片
					tempCtx.drawImage(img, 0, 0, tempCanvas.width, tempCanvas.height)
					// 绘制canvas内容
					tempCtx.drawImage(canvasRef.value!, 0, 0)
					// 返回合并后的数据
					resolve(tempCanvas.toDataURL('image/png'))
				}
				img.onerror = () => {
					// 如果图片加载失败，只返回canvas内容
					resolve(canvasRef.value!.toDataURL('image/png'))
				}
				img.src = BaseUrl + props.info.image[0]
			})
		} else {
			// 没有背景图片，直接返回canvas内容
			return Promise.resolve(canvasRef.value.toDataURL('image/png'))
		}
	}
	return Promise.resolve(null)
}

function loadCanvasData(dataUrl: string) {
	if (canvasRef.value && dataUrl) {
		const ctx = canvasRef.value.getContext('2d')!
		const img = new Image()
		img.onload = () => {
			// 清空canvas
			ctx.clearRect(0, 0, canvasRef.value!.width, canvasRef.value!.height)
			// 直接绘制保存的图片（已包含背景图片和绘制内容）
			ctx.drawImage(img, 0, 0)
			// 标记为已有绘制内容
			hasDrawn.value = true
		}
		img.src = dataUrl
	}
}

function resetDrawnState() {
	hasDrawn.value = false
}

defineExpose({
	getCanvasData,
	clearCanvas,
	loadCanvasData,
	resetDrawnState
})

onMounted(async () => {
	// 初始化翻译
	await initTranslations()
	
	// 初始化画笔颜色为主题色
	const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--theme-primary')
	if (themeColor) {
		strokeStyle.value = themeColor
	}
	
	console.log('CanvasBord mounted with props:', props.info);
	console.log('Image array:', props.info.image);
	console.log('Type:', props.info.type);
	
	nextTick(() => {
		resizeCanvas()
		window.addEventListener('resize', resizeCanvas)
	})
})
</script>

<style scoped>
.canvas-title {
	width: 100%;
	padding: 10px 0;
	text-align: center;
	font-size: 30px;
	margin: 0;
	background-color: rgba(0, 0, 0, 0.2);
}
.canvas-toolbar {
	padding: 12px;
	border-bottom: 3px solid #e0e0e0;
	display: flex;

	align-items: center;
	background: #f7fafd;
}

.tool-group {
	display: flex;
	align-items: center;
	gap: 10px;
}

.tool-btn {
	background: #fff;
	border: 1.5px solid var(--theme-primary);
	color: var(--theme-primary);
	border-radius: 6px;
	padding: 6px 16px;
	font-size: 15px;
	cursor: pointer;
	transition: background 0.2s, color 0.2s, border 0.2s;
	display: flex;
	align-items: center;
	gap: 4px;
}

.tool-btn.active {
	background: var(--theme-primary);
	color: #fff;
}

.clear-btn {
	border-color: #e57373;
	color: #e57373;
}

.clear-btn:hover {
	background: #e57373;
	color: #fff;
}

.color-label input[type='color'] {
	width: 32px;
	height: 32px;
	border: none;
	background: none;
	padding: 0;
	cursor: pointer;
}

.slider {
	margin: 0 8px;
}

.brush-size {
	font-size: 15px;
	color: #888;
	margin-left: 8px;
	min-width: 40px;
	text-align: center;
}

.canvas-wrap {
	width: 60vw;
	background-color: #fff;
	border: 1px solid #eee;
	display: flex;
	align-items: stretch;
}

.canvas-cursor-wrap {
	position: relative;
	height: 43vh; /* 减去工具栏高度 */
	width: 100%;
}

.canvas-cursor {
	position: absolute;
	pointer-events: none;
	border-radius: 50%;
	z-index: 10;
	box-sizing: border-box;
}

canvas {
	background: transparent;
	cursor: none !important;
	width: 100%;
	display: block;
}

.quick-colors,
.quick-sizes {
	display: flex;
	align-items: center;
	gap: 6px;
	margin-right: 10px;
}

.color-dot {
	width: 22px;
	height: 22px;
	border-radius: 50%;
	display: inline-block;
	cursor: pointer;
	border: 2px solid #fff;
	box-sizing: border-box;
	transition: border 0.2s;
}

.size-dot {
	border-radius: 50%;
	display: inline-block;
	cursor: pointer;
	margin-right: 2px;
	background: var(--theme-primary);
	transition: border 0.2s;
}
</style>